package okhttp3.internal.platform.ohos;

import okhttp3.Protocol;

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.X509TrustManager;
import java.util.List;

public class DeferredSocketAdapter implements SocketAdapter {
    private Factory socketAdapterFactory;
    private SocketAdapter delegate = null;

    public DeferredSocketAdapter(Factory socketAdapterFactory) {
        this.socketAdapterFactory = socketAdapterFactory;
    }

    @Override
    public Boolean isSupported() {
        return true;
    }

    @Override
    public Boolean matchesSocket(SSLSocket sslSocket) {
        return socketAdapterFactory.matchesSocket(sslSocket);
    }


    @Override
    public void configureTlsExtensions(SSLSocket sslSocket, String hostname, List<Protocol> protocols) {
        SocketAdapter socketAdapter = this.getDelegate(sslSocket);
        if (socketAdapter != null) {
            socketAdapter.configureTlsExtensions(sslSocket, hostname, protocols);
        }
    }

    @Override
    public String getSelectedProtocol(SSLSocket sslSocket) {
        SocketAdapter socketAdapter = this.getDelegate(sslSocket);
        return socketAdapter != null ? socketAdapter.getSelectedProtocol(sslSocket) : null;
    }

    private final synchronized SocketAdapter getDelegate(SSLSocket sslSocket) {
        if (this.delegate == null && this.socketAdapterFactory.matchesSocket(sslSocket)) {
            this.delegate = this.socketAdapterFactory.create(sslSocket);
        }

        return this.delegate;
    }

    @Override
    public X509TrustManager trustManager(SSLSocketFactory sslSocketFactory) {
        return null;
    }


    @Override
    public Boolean matchesSocketFactory(SSLSocketFactory sslSocketFactory) {
        return null;
    }


    interface Factory {
        Boolean matchesSocket(SSLSocket sslSocket);

        SocketAdapter create(SSLSocket sslSocket);
    }
}
